package com.bw.common.mvi

import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.LogUtils
import com.bw.common.mvi.state.MutableContainer
import com.bw.common.mvi.state.RealContainer
import com.bw.common.mvi.state.UiState
import com.bw.network.BaseEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*

abstract class BaseViewModel<REPO : BaseRespository,STATE : UiState> : ViewModel() {
    protected lateinit var repo : REPO
    private var state : STATE = createState()
    private var _mutableContainer : MutableContainer<STATE> = RealContainer(state)
    var mutableContainer: MutableContainer<STATE> = _mutableContainer
    abstract fun createRepo():REPO
    abstract fun createState():STATE
    init {
        repo = createRepo()
    }

    protected fun subFlow(flow: Flow<BaseEntity>): Flow<BaseEntity> {
        return flow.flowOn(Dispatchers.IO)
            .catch { t : Throwable->
                LogUtils.e("errorMsg:${t.message}") }
            .onStart { mutableContainer.updateRequestState { copy(request=true,complate = false) } }
            .onCompletion { mutableContainer.updateRequestState { copy(request=false,complate = true) } }
    }
}